package com.kakahair.common.util.handler;

import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {


	    @Override
	    public void setNonNullParameter(PreparedStatement ps, int i, String[] ts, JdbcType jdbcStringype) throws SQLException {
	        StringBuffer result = new StringBuffer();
	        for (String value : ts) {
	            result.append(value).append(",");
	        }
	        result.deleteCharAt(result.length() - 1);
	        ps.setString(i, result.toString());
	    }

	    public String[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
	        return toArray(resultSet.getString(columnName));
	    }

	    public String[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
	        return toArray(resultSet.getString(columnIndex));
	    }

	    public String[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
	        return toArray(callableStatement.getString(columnIndex));
	    }

	    String[] toArray(String columnValue) {
	        if (columnValue == null) {
	            return createArray(0);
	        }
	        String[] values = columnValue.split(",");
	        return values;
	    }

	    String[] createArray(int size) {
	        return (String[]) Array.newInstance(String.class, size);
	    }
}
